package generate;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

/** This class generates the keys and PIN numbers for
 *  Alice, Bob and Carol */

public class Generator {

	public static void main(String[] args) {

		Random seed = new Random();
		KeyGenerator keyGenerator;
		SecretKey[] myKeys = new SecretKey[3];
		SecretKey[] myIVs = new SecretKey[3];
		String[] users = {"Alice", "Bob", "Carol"};
		String[] pins = new String[3];

		// Generate keys and IVs
		for (int index = 0; index < 3; index++) {
			try{
				keyGenerator = KeyGenerator.getInstance("AES");
				myKeys[index] = keyGenerator.generateKey();
				myIVs[index] = keyGenerator.generateKey();

			}catch(NoSuchAlgorithmException e){
				e.printStackTrace();
			}
		}

		// Generate PINs
		for (int index = 0; index < 3; index++) {
			String pin = "";
			for (int count = 0; count < 4; count++) {
				pin += seed.nextInt(10);
			}

			pins[index] = pin;
		}

		//	Write out PINs and keys

		for (int index = 0; index < 3; index++) {
			
			String key_string = "";
			for (byte b : myKeys[index].getEncoded()) {
				key_string += String.format("%02X", b);
			}
			
			String iv_string = "";
			for (byte b : myIVs[index].getEncoded()) {
				iv_string += String.format("%02X", b);
			}

			try {
				PrintWriter outputFile = new PrintWriter(new File(users[index] + ".card"));
				outputFile.print(key_string);
				outputFile.print("\t");
				outputFile.print(iv_string);
				outputFile.flush();
				outputFile.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			
			try {
				PrintWriter outputFile = new PrintWriter(new File(users[index] + "PIN.txt"));
				outputFile.print(pins[index]);
				outputFile.flush();
				outputFile.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		
		// Generate Bank Key
		SecretKey bankKey = null;
		SecretKey bankIV = null;
		try{
			keyGenerator = KeyGenerator.getInstance("AES");
			bankKey = keyGenerator.generateKey();
			bankIV = keyGenerator.generateKey();

		}catch(NoSuchAlgorithmException e){
			e.printStackTrace();
		}
		
		String key_string = "";
		for (byte b : bankKey.getEncoded()) {
			key_string += String.format("%02X", b);
		}
		
		String iv_string = "";
		for (byte b : bankIV.getEncoded()) {
			iv_string += String.format("%02X", b);
		}

		try {
			PrintWriter outputFile = new PrintWriter(new File("bank.card"));
			outputFile.print(key_string);
			outputFile.print("\t");
			outputFile.print(iv_string);
			outputFile.flush();
			outputFile.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

}
